package com.googlecode.microanalyst.designer.figures;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.eclipse.draw2d.ConnectionAnchor;
import org.eclipse.draw2d.Figure;
import org.eclipse.draw2d.geometry.Point;

public class ConnectedFigure extends Figure {

	protected Map<String, ConnectionAnchor> connectionAnchors = new HashMap<String, ConnectionAnchor>();
	protected List<ConnectionAnchor> inputConnectionAnchors = new ArrayList<ConnectionAnchor>(2);
	protected List<ConnectionAnchor> outputConnectionAnchors = new ArrayList<ConnectionAnchor>(2);

	public ConnectionAnchor connectionAnchorAt(Point p) {
		ConnectionAnchor closest = null;
		long min = Long.MAX_VALUE;

		List<ConnectionAnchor> connectionAnchors = getSourceConnectionAnchors();
		for (ConnectionAnchor c : connectionAnchors) {
			Point p2 = c.getLocation(null);
			long d = p.getDistance2(p2);
			if (d < min) {
				min = d;
				closest = c;
			}
		}
		connectionAnchors = getTargetConnectionAnchors();
		for (ConnectionAnchor c : connectionAnchors) {
			Point p2 = c.getLocation(null);
			long d = p.getDistance2(p2);
			if (d < min) {
				min = d;
				closest = c;
			}
		}
		return closest;
	}

	public ConnectionAnchor getConnectionAnchor(String terminal) {
		return (ConnectionAnchor) connectionAnchors.get(terminal);
	}

	public String getConnectionAnchorName(ConnectionAnchor c) {
		Set<String> keys = connectionAnchors.keySet();
		for (String key : keys) {
			if (connectionAnchors.get(key).equals(c))
				return key;
		}
		return null;
	}

	public ConnectionAnchor getSourceConnectionAnchorAt(Point p) {
		ConnectionAnchor closest = null;
		long min = Long.MAX_VALUE;

		List<ConnectionAnchor> connectionAnchors = getSourceConnectionAnchors();
		for (ConnectionAnchor c : connectionAnchors) {
			Point p2 = c.getLocation(p);
			long d = p.getDistance2(p2);
			if (d < min) {
				min = d;
				closest = c;
			}
		}
		return closest;
	}

	public List<ConnectionAnchor> getSourceConnectionAnchors() {
		return outputConnectionAnchors;
	}

	public ConnectionAnchor getTargetConnectionAnchorAt(Point p) {
		ConnectionAnchor closest = null;
		long min = Long.MAX_VALUE;

		List<ConnectionAnchor> connectionAnchors = getTargetConnectionAnchors();
		for (ConnectionAnchor c : connectionAnchors) {
			Point p2 = c.getLocation(p);
			long d = p.getDistance2(p2);
			if (d < min) {
				min = d;
				closest = c;
			}
		}
		return closest;
	}

	public List<ConnectionAnchor> getTargetConnectionAnchors() {
		return inputConnectionAnchors;
	}

}
